<?php

namespace Hilaoyu\LaravelExtend\Services\Files\Controllers;

use Hilaoyu\LaravelExtend\Services\Files\FileService;
use Illuminate\Routing\MiddlewareNameResolver;
use Illuminate\Routing\Pipeline;
use Illuminate\Http\Request;


trait FilesControllerHelperTrait
{

    /**
     * @return array
     */
    protected function formatMiddleware($middleware){
        $route_middlewares = $this->httpKernel()->getRouteMiddleware();
        $route_middleware_groups = $this->httpKernel()->getMiddlewareGroups();
        //$middleware = FileService::getDiskConfig($disk,'allow_upload.middleware',[]);
        return collect($middleware)->map(function ($name) use ($route_middlewares,$route_middleware_groups) {
            return (array) MiddlewareNameResolver::resolve($name, $route_middlewares,$route_middleware_groups);
        })->flatten()->all();
    }

    /**
     * @param Request $request
     * @param $disk
     * @return Pipeline
     */
    protected function checkAllowUpload(Request $request,$disk){
        if(!FileService::getDiskConfig($disk,'allow_upload',null)){
            abort(404);
        }

        $request->offsetSet('laravel_extend_files_disk',$disk);
        return (new Pipeline(app()))
            ->send($request)
            ->through($this->formatMiddleware(FileService::getDiskConfig($disk,'allow_upload.middleware',[])));
    }
    protected function checkAllowView(Request $request,$disk){
        if('public' != FileService::getDiskConfig($disk,'visibility') && !FileService::getDiskConfig($disk,'allow_view',null)){
            abort(404);
        }

        $request->offsetSet('laravel_extend_files_disk',$disk);
        return (new Pipeline(app()))
            ->send($request)
            ->through($this->formatMiddleware(FileService::getDiskConfig($disk,'allow_view.middleware',[])));
    }


}
